<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="100px" style="max-width: 800px">
    <el-form-item label="密码" prop="password">
      <el-input v-model.trim="user.password" show-password />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model.trim="user.confirmPassword" show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { userPassword } from '@/api/user'
import { validatePsdReg } from '@/utils/validate'
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      user: {
        id: null,
        password: '',
        confirmPassword: ''
      },
      rules: {
        password: [
          { required: true, trigger: 'blur', validator: validatePsdReg }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', validator: validatePsdReg },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.user = this.$store.getters.userInfo
  },
  methods: {
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const tempData = {
            password: this.user.password,
            confirmPassword: this.user.confirmPassword
          }
          userPassword(tempData).then(() => {
            this.$message({
              title: '提示',
              message: '密码修改成功，请牢记',
              type: 'success',
              duration: 2000
            })
            this.user.password = ''
            this.user.confirmPassword = ''
          })
        }
      })
    }
  }
}
</script>
